package com.hongguowei.upload;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "ali.oss")
public class ALiOssTemplate {
    /**
     * 访问站点
     */
    private String endpoint;
    /**
     *用户名
     */
    private String accessKeyId;
    /**
     *密码
     */
    private String accessKeySecret;
    /**
     *存储空间名
     */
    private String bucketName;
    /**
     *类型
     */
    private String storageArea;

    public String uploadFileToOss(OssBo ossBO) {

        InputStream inputStream = ossBO.getInputStream();
        String fileName = ossBO.getFileName();

        String currentDateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString();
        // 文件：存储区域/日期/uuid.文件后缀
        String newRenameFile = storageArea + "/" + currentDateStr + "/" + newFileName + fileExtension;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, newRenameFile, inputStream);
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        //https://classroomsys.oss-cn-beijing.aliyuncs.com/objectdir/a.png
        return "https://" + bucketName + "." + endpoint + "/" + newRenameFile;
    }
}